package com.societyGames.loading 
{
	import com.societyGames.system.EventObject;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	/**
	 * Manages a series of load steps until complete.
	 * @author 
	 */
	public class LoadQueue extends EventDispatcher 
	{
		private var _completeEventObject:EventObject;
		private var _currentLoadStep:ILoadStep;
		private var _currentLoadStepIndex:int = -1;
		private var _loadSteps:Vector.<ILoadStep> = new Vector.<ILoadStep>();
		
		public function LoadQueue() 
		{
			this._completeEventObject = new EventObject(this, "COMPLETE");
		}
		
		public function add(loadStep:ILoadStep):void
		{
			this._loadSteps.push(loadStep);
		}
		
		public function load():void
		{
			if (this._currentLoadStep != null)
			{
				throw new Error("Another load is already in progress.");
			}
			onLoadComplete(null);
		}
		
		public function get completeEventObject():EventObject
		{
			return this._completeEventObject;
		}
		
		private function onLoadComplete(event:Event):void
		{
			if (this._currentLoadStep != null)
			{
				this._currentLoadStep.completeEventObject.removeEventListener(onLoadComplete);
			}
			this._currentLoadStepIndex++;
			if (this._currentLoadStepIndex == this._loadSteps.length)
			{
				this._currentLoadStepIndex = -1;
				this._currentLoadStep = null;
				this._loadSteps.length = 0;
				this._completeEventObject.dispatchEvent();
			}
			else
			{
				this._currentLoadStep = this._loadSteps[this._currentLoadStepIndex];
				this._currentLoadStep.completeEventObject.addEventListener(onLoadComplete);
				this._currentLoadStep.load();
			}
		}
	}
}